package org.jivesoftware;

import java.io.IOException;
import java.io.OutputStream;
import java.lang.annotation.Annotation;
import java.lang.reflect.Type;

import javax.ws.rs.Produces;
import javax.ws.rs.WebApplicationException;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.ext.MessageBodyWriter;
import javax.ws.rs.ext.Provider;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;

@Provider 
@Produces("application/json") 
public class JsonWriterProvider implements MessageBodyWriter<Object > {

    private final Gson gson; 
    
    public JsonWriterProvider(){
    	gson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().setDateFormat( 
        "yyyy-MM-dd").create();  
    }
	@Override
	public long getSize(Object  arg0, Class<?> arg1, Type arg2,
			Annotation[] arg3, MediaType arg4) {
		// TODO Auto-generated method stub
		return -1;
	}

	@Override
	public boolean isWriteable(Class<?> arg0, Type arg1, Annotation[] arg2,
			MediaType arg3) {
		// TODO Auto-generated method stub
		if(arg3.equals(MediaType.APPLICATION_JSON_TYPE))
			return true;
		return false;
	}

	@Override
	public void writeTo(Object  arg0, Class<?> arg1, Type arg2,
			Annotation[] arg3, MediaType arg4,
			MultivaluedMap<String, Object> arg5, OutputStream arg6)
			throws IOException, WebApplicationException {
		// TODO Auto-generated method stub
		arg6.write(gson.toJson(arg0, arg2).getBytes("UTF-8")); 
	}
	
}
